<%#
 Copyright 2013-2020 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
package <%= packageName %>.security;

<%_ if (databaseType === 'cassandra') { _%>
import <%= packageName %>.AbstractCassandraTest;
<%_ } _%>
<%_ if (databaseType === 'neo4j') { _%>
import <%= packageName %>.AbstractNeo4jIT;
<%_ } _%>
<%_ if (cacheProvider === 'redis') { _%>
import <%= packageName %>.RedisTestContainerExtension;
<%_ } _%>
<%_ if (reactiveSqlTestContainers) { _%>
import <%= packageName %>.ReactiveSqlTestContainerExtension;
<%_ } _%>
import <%= packageName %>.<%= mainClass %>;
<%_ if (databaseType === 'sql' && reactive) { _%>
import <%= packageName %>.config.Constants;
<%_ } _%>
import <%= packageName %>.domain.<%= asEntity('User') %>;
import <%= packageName %>.repository.UserRepository;

import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
<%_ if (databaseType === 'neo4j' || cacheProvider === 'redis' || reactiveSqlTestContainers) { _%>
import org.junit.jupiter.api.extension.ExtendWith;
<%_ } _%>
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
<%_ if (reactive) { _%>
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
<%_ } _%>
import org.springframework.security.core.userdetails.UserDetails;
<%_ if (!reactive) { _%>
import org.springframework.security.core.userdetails.UserDetailsService;
<%_ } _%>
<%_ if (databaseType === 'couchbase') { _%>
import org.springframework.security.test.context.support.WithMockUser;
<%_ } _%>
<%_ if (databaseType === 'sql' && !reactive) { _%>
import org.springframework.transaction.annotation.Transactional;
<%_ } _%>

<%_ if (databaseType === 'cassandra') { _%>
import java.util.UUID;
<%_ } _%>
import java.util.Locale;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

/**
 * Integrations tests for {@link DomainUserDetailsService}.
 */
@SpringBootTest(classes = <%= mainClass %>.class)
<%_ if (cacheProvider === 'redis') { _%>
@ExtendWith(RedisTestContainerExtension.class)
<%_ } _%>
<%_ if (databaseType === 'neo4j') { _%>
@ExtendWith(AbstractNeo4jIT.class)
<%_ } _%>
<%_ if (reactiveSqlTestContainers) { _%>
@ExtendWith(ReactiveSqlTestContainerExtension.class)
<%_ } _%>
<%_ if (databaseType === 'sql' && !reactive) { _%>
@Transactional
<%_ } _%>
<%_ if (databaseType === 'couchbase') { _%>
@WithMockUser("test-user-one")
<%_ } _%>
class DomainUserDetailsServiceIT <% if (databaseType === 'cassandra') { %>extends AbstractCassandraTest <% } %>{

    private static final String USER_ONE_LOGIN = "test-user-one";
    private static final String USER_ONE_EMAIL = "test-user-one@localhost";
    private static final String USER_TWO_LOGIN = "test-user-two";
    private static final String USER_TWO_EMAIL = "test-user-two@localhost";
    private static final String USER_THREE_LOGIN = "test-user-three";
    private static final String USER_THREE_EMAIL = "test-user-three@localhost";

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private <% if (reactive) { %>Reactive<% } %>UserDetailsService domainUserDetailsService;

    @BeforeEach
    public void init() {
        <%_ if (databaseType === 'sql' && reactive) { _%>
        userRepository.deleteAllUserAuthorities().block();
        <%_ } _%>
        <%_ if (databaseType !== 'sql' || reactive) { _%>
        userRepository.deleteAll()<% if (reactive) { %>.block()<% } %>;

        <%_ } _%>
        <%= asEntity('User') %> userOne = new <%= asEntity('User') %>();
        <%_ if (databaseType === 'cassandra') { _%>
        userOne.setId(UUID.randomUUID().toString());
        <%_ } _%>
        userOne.setLogin(USER_ONE_LOGIN);
        userOne.setPassword(RandomStringUtils.random(60));
        userOne.setActivated(true);
        userOne.setEmail(USER_ONE_EMAIL);
        userOne.setFirstName("userOne");
        userOne.setLastName("doe");
        userOne.setLangKey("en");
        <%_ if (databaseType === 'sql' && reactive) { _%>
        userOne.setCreatedBy(Constants.SYSTEM_ACCOUNT);
        <%_ } _%>
        userRepository.save(userOne)<% if (reactive) { %>.block()<% } %>;

        <%= asEntity('User') %> userTwo = new <%= asEntity('User') %>();
        <%_ if (databaseType === 'cassandra') { _%>
        userTwo.setId(UUID.randomUUID().toString());
        <%_ } _%>
        userTwo.setLogin(USER_TWO_LOGIN);
        userTwo.setPassword(RandomStringUtils.random(60));
        userTwo.setActivated(true);
        userTwo.setEmail(USER_TWO_EMAIL);
        userTwo.setFirstName("userTwo");
        userTwo.setLastName("doe");
        userTwo.setLangKey("en");
        <%_ if (databaseType === 'sql' && reactive) { _%>
        userTwo.setCreatedBy(Constants.SYSTEM_ACCOUNT);
        <%_ } _%>
        userRepository.save(userTwo)<% if (reactive) { %>.block()<% } %>;

        <%= asEntity('User') %> userThree = new <%= asEntity('User') %>();
        <%_ if (databaseType === 'cassandra') { _%>
        userThree.setId(UUID.randomUUID().toString());
        <%_ } _%>
        userThree.setLogin(USER_THREE_LOGIN);
        userThree.setPassword(RandomStringUtils.random(60));
        userThree.setActivated(false);
        userThree.setEmail(USER_THREE_EMAIL);
        userThree.setFirstName("userThree");
        userThree.setLastName("doe");
        userThree.setLangKey("en");
        <%_ if (databaseType === 'sql' && reactive) { _%>
        userThree.setCreatedBy(Constants.SYSTEM_ACCOUNT);
        <%_ } _%>
        userRepository.save(userThree)<% if (reactive) { %>.block()<% } %>;
    }

    @Test
    void assertThatUserCanBeFoundByLogin() {
        UserDetails userDetails = domainUserDetailsService.<% if (reactive) { %>find<% } else { %>loadUser<% } %>ByUsername(USER_ONE_LOGIN)<% if (reactive) { %>.block()<% } %>;
        assertThat(userDetails).isNotNull();
        assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN);
    }

    @Test
    void assertThatUserCanBeFoundByLoginIgnoreCase() {
        UserDetails userDetails = domainUserDetailsService.<% if (reactive) { %>find<% } else { %>loadUser<% } %>ByUsername(USER_ONE_LOGIN.toUpperCase(Locale.ENGLISH))<% if (reactive) { %>.block()<% } %>;
        assertThat(userDetails).isNotNull();
        assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN);
    }

    @Test
    void assertThatUserCanBeFoundByEmail() {
        UserDetails userDetails = domainUserDetailsService.<% if (reactive) { %>find<% } else { %>loadUser<% } %>ByUsername(USER_TWO_EMAIL)<% if (reactive) { %>.block()<% } %>;
        assertThat(userDetails).isNotNull();
        assertThat(userDetails.getUsername()).isEqualTo(USER_TWO_LOGIN);
    }

    @Test
    void assertThatUserCanBeFoundByEmailIgnoreCase() {
        UserDetails userDetails = domainUserDetailsService.<% if (reactive) { %>find<% } else { %>loadUser<% } %>ByUsername(USER_TWO_EMAIL.toUpperCase(Locale.ENGLISH))<% if (reactive) { %>.block()<% } %>;
        assertThat(userDetails).isNotNull();
        assertThat(userDetails.getUsername()).isEqualTo(USER_TWO_LOGIN);
    }

    @Test
    void assertThatEmailIsPrioritizedOverLogin() {
        UserDetails userDetails = domainUserDetailsService.<% if (reactive) { %>find<% } else { %>loadUser<% } %>ByUsername(USER_ONE_EMAIL)<% if (reactive) { %>.block()<% } %>;
        assertThat(userDetails).isNotNull();
        assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN);
    }

    @Test
    void assertThatUserNotActivatedExceptionIsThrownForNotActivatedUsers() {
        assertThatExceptionOfType(UserNotActivatedException.class).isThrownBy(
            () -> domainUserDetailsService.<% if (reactive) { %>find<% } else { %>loadUser<% } %>ByUsername(USER_THREE_LOGIN)<% if (reactive) { %>.block()<% } %>);
    }

}
